/**
 * ...
 * @author Franco Ponticelli
 */

package uform.model.cell;
import uform.model.cell.Cell;
import thx.util.Result;
import uform.model.value.ValueType;
import thx.error.Error;
using thx.util.Results;

class ValueCell<T> extends Cell<T, T>
{
	static var _reNull  = ~/^\s*null\s*/m;
	
	var _optional : Bool;
	public function new(type : ValueType<T>, optional = false)
	{
		super(type);
		setOptional(optional);
	}
	
	public function setOptional(optional : Bool)
	{
		_optional = optional;
	}
	
	override function isOptional()
	{
		return _optional;
	}
	
	override function validate(value : Dynamic) : Result
	{
		if (null == value || "" == value)
		{
			if (_optional)
			{
				return Result.Ok;
			} else {
				return "null value not allowed".failure();
			}
		} else {
			var r = type.validateType(value);
			switch(r)
			{
				case Ok:
					return type.validate(value);
				default:
					return r;
			}
		}
	}
	
	override function parse(s : String, ?ref : { s : String }) : T
	{
		if (_reNull.match(s))
		{
			if (null != ref)
				ref.s = _reNull.matchedRight();
			return null;
		} else
			return type.parse(s, ref);
	}
	
	override function render(value : T) : String
	{
		return type.render(value);
	}
	
	override function toString()
	{
		return "ValueCell { " + (_optional ? "optional" : "mandatory") + ", type : " + type.toString() + " }";
	}
}